package com.winway.sixbook.ui;
  
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.AlertDialog;  
import com.winway.sixbook.HomeActivity;
import com.winway.sixbook.R;
import com.winway.sixbook.custom.CloseActivityClass;
import com.winway.sixbook.custom.MySimpleCursorAdapter;
import com.winway.sixbook.service.RecordDataManager;
import android.app.Activity;  
import android.app.AlertDialog;
import android.app.Dialog;   
import android.os.Bundle;   
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;  
import android.graphics.Bitmap;
import android.os.Bundle;  
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListAdapter;  
import android.widget.ListView;  
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
  
public class GridActivity extends Activity {  
  
	private String TAG ="GridActivity";
    ListView lv;
    private ImageButton top_tbn_fanhui;
    private Button top_tbn_xinzeng,navigate_btn_jt;
	private TextView title,jrzhnr,jrzygnr,jrqynr,bottom_recordid;
	
    RecordDataManager recordDataManager ;
    LinearLayout bottom;
    private View grid_bottomView;
    
    private Button navigate_btn_export;
	private final int LISTDIALOG = 1;
	String addtime = "";
	private Boolean istoday = true;
  
    @Override  
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_grid); 
        CloseActivityClass.activityList.add(this);
        
        if (recordDataManager == null) {
        	recordDataManager = new RecordDataManager(this);
        	recordDataManager.openDataBase();
        }
        lv = (ListView) findViewById(R.id.lv); 
        top_tbn_fanhui = (ImageButton)findViewById(R.id.nagivate_btn_left);
        top_tbn_xinzeng = (Button)findViewById(R.id.navigate_btn_right);
        title = (TextView)findViewById(R.id.title);
        navigate_btn_export = (Button)findViewById(R.id.navigate_btn_export);
        navigate_btn_jt =  (Button)findViewById(R.id.navigate_btn_jt);
        
        top_tbn_fanhui.setOnClickListener(mListener);
        
    	Bundle bundle = new Bundle();
        bundle = this.getIntent().getExtras();
        if(null!= bundle && null != bundle.getString("Addtime")){
        	addtime = bundle.getString("Addtime");
        }
        SimpleDateFormat dateformat1=new SimpleDateFormat("yyyy-MM-dd");
        if(dateformat1.format(new Date()).equals(addtime)){
        	title.setText("今天");
        	istoday= true;
        	top_tbn_xinzeng.setOnClickListener(mListener);
        }else{
        	title.setText("历史");
        	istoday= false;
        	top_tbn_xinzeng.setVisibility(View.INVISIBLE);
        }
        
        navigate_btn_export.setOnClickListener(mListener);
        navigate_btn_jt.setOnClickListener(mListener);
        updatelistview(addtime);
    }  
  
    // 更新listview  
    public void updatelistview(String addtime) {  
    	
        Cursor cr = recordDataManager.findCommonRecordByTime(addtime);  
        
        String recordid = cr.getColumnName(0);// 获取第0列 
        String zzjl = cr.getColumnName(4);// 获取第4列 
        String sj_hour = cr.getColumnName(7);
        String sj_min = cr.getColumnName(8);
        String zmString = cr.getColumnName(2);
        String fmsString = cr.getColumnName(9);
        String wysString = cr.getColumnName(10);
        String sj_sec = cr.getColumnName(12);
        
        String[] ColumnNames = { recordid, zzjl, sj_hour, sj_min, sj_sec,zmString, fmsString , wysString }; 
  
        ListAdapter adapter = new MySimpleCursorAdapter(this,  
                R.layout.listviewlayout, cr, ColumnNames,
                new int[] {R.id.recordid, R.id.zzjl, R.id.sj_hour ,R.id.sj_min,R.id.sj_sec, R.id.zmstr, R.id.fmstr , R.id.wystr});  
        // layout为listView的布局文件，包括三个TextView，用来显示三个列名所对应的值  
        // ColumnNames为数据库的表的列名  
        // 最后一个参数是int[]类型的，为view类型的id，用来显示ColumnNames列名所对应的值。view的类型为TextView  \
        
        int count=recordDataManager.findZuihaoRecordCount(addtime);
		if(count>0){
			// 加载底部布局grid_bottom 
	        grid_bottomView = View.inflate(this, R.layout.grid_bottom, null); 
	        
	        jrzhnr= (TextView)grid_bottomView.findViewById(R.id.jrzhnr);//今日最好内容
	        jrzygnr= (TextView)grid_bottomView.findViewById(R.id.jrzygnr);//今日最要改内容
	        jrqynr= (TextView)grid_bottomView.findViewById(R.id.jrqynr);//今日祈愿内容
	        bottom_recordid = (TextView)grid_bottomView.findViewById(R.id.newrecordid);
	        updatebottom(addtime);
	        lv.addFooterView(grid_bottomView);
		}else{
			// 加载底部布局grid_bottom 
	        grid_bottomView = View.inflate(this, R.layout.listview_bottom, null); 
	        lv.addFooterView(grid_bottomView);
		}
        lv.setAdapter(adapter);
        
        lv.setOnItemClickListener(new OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				TextView recordid=(TextView)arg1.findViewById(R.id.recordid);
				if(recordid!=null ){
					if(recordid.getText()!=null){
						Cursor recorddata = recordDataManager.fetchRecordData(Integer.parseInt(""+recordid.getText()));
						if(null != recorddata){
							Intent intent = new Intent(GridActivity.this, NewRecordAdd.class);
							Bundle bundle = new Bundle(); 
							bundle.putString("typename", recorddata.getString(recorddata.getColumnIndex("type_name")));
							bundle.putString("typeid", recorddata.getString(recorddata.getColumnIndex("type_id")));
							bundle.putString("recorddataid", ""+recordid.getText());
							intent.putExtras(bundle);
							startActivity(intent);
						}
					}
				}else{
					recordid=(TextView)arg1.findViewById(R.id.newrecordid);
					if(recordid!=null ){
						if(recordid.getText()!=null){
							Cursor recorddata = recordDataManager.fetchRecordData(Integer.parseInt(""+recordid.getText()));
							if(null != recorddata){
								Intent intent = new Intent(GridActivity.this, NewRecordAdd.class);
								Bundle bundle = new Bundle(); 
								bundle.putString("typename", recorddata.getString(recorddata.getColumnIndex("type_name")));
								bundle.putString("typeid", recorddata.getString(recorddata.getColumnIndex("type_id")));
								bundle.putString("recorddataid", ""+recordid.getText());
								intent.putExtras(bundle);
								startActivity(intent);
							}
						}
					}
				}
			}
		});
       
    }
    
    public void updatebottom(String addtime){
    	
    	Cursor cursor = recordDataManager.findZuihaoRecord(addtime);
    	if(null != cursor){
            if(cursor.moveToFirst() ){
                do{
                	jrzhnr.setText(cursor.getString(cursor.getColumnIndex("content_zm")));
                	jrzygnr.setText(cursor.getString(cursor.getColumnIndex("content_fm")));
                	jrqynr.setText(cursor.getString(cursor.getColumnIndex("content_wy")));
                	bottom_recordid.setText(cursor.getString(cursor.getColumnIndex("_id")));
                }while( cursor.moveToNext());
            }
		 }
    	
    }
    OnClickListener mListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.nagivate_btn_left:
				Intent counter = new Intent(GridActivity.this, HomeActivity.class);
				startActivity(counter);
				finish();
				break;
			case R.id.navigate_btn_right:
				int count=recordDataManager.findSeedsCount();
				if(count>0){
					Intent counter4 = new Intent(GridActivity.this, GridViewChooose.class);
					startActivity(counter4);
					finish();
				}else{
					Toast.makeText(GridActivity.this, R.string.type_empty,Toast.LENGTH_SHORT).show();
					return ;
				}
				break;
			case R.id.navigate_btn_export:
				//导出按钮
				Log.v(TAG, "export");
//				showDialog(LISTDIALOG); 
				Intent export = new Intent(GridActivity.this, ExportSet.class);
				Bundle bundle = new Bundle(); 
				bundle.putString("Addtime", addtime);
				export.putExtras(bundle); 
				startActivity(export);
				finish();
				break;
			case R.id.navigate_btn_jt:
				//截图按钮
				Log.v(TAG, "截图");
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
				String fname = "/sdcard/"+ sdf.format(new Date()) + ".png";
				//String fname = "/data/data/com.winway.sixbook/"+ sdf.format(new Date()) + ".png";
				View view = v.getRootView();
				view.setDrawingCacheEnabled(true);
		        view.buildDrawingCache();

				Bitmap bitmap = view.getDrawingCache();

				if(bitmap != null){
					
					 
					 
					System.out.println("bitmap got!");
					try{
			            FileOutputStream out = new FileOutputStream(fname);
			            bitmap.compress(Bitmap.CompressFormat.PNG,100,out);
			            
			            Dialog alertDialog = new AlertDialog.Builder(GridActivity.this).setTitle("操作成功").setMessage("文件在sd卡根目录，名称为"+sdf.format(new Date()) + ".png"). setIcon(R.drawable.ic_launcher).create();
			           
 
			            alertDialog.show();   
			            System.out.println("file" + fname + "output done.");
			          }catch(Exception e) {
			            e.printStackTrace();
			          }
				}else{
					System.out.println("bitmap is NULL!");
			    }
				break;
			}
		}
	};
  
	@Override
	protected void onResume() {
		if (recordDataManager == null) {
			recordDataManager = new RecordDataManager(this);
			recordDataManager.openDataBase();
        }
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		if (recordDataManager != null) {
			recordDataManager.closeDataBase();
			recordDataManager = null;
        }
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		if (recordDataManager != null) {
			recordDataManager.closeDataBase();
			recordDataManager = null;
        }
		super.onPause();
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;
		switch(id) {
			case LISTDIALOG:
				Builder builder = new AlertDialog.Builder(this);
				builder.setTitle("导出功过格");
				builder.setIcon(R.drawable.ic_export);
				DialogInterface.OnClickListener listener = 
					new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialogInterface,  int which) {
							if("按种子日期导出".equals(getResources().getStringArray(R.array.hobby)[which])){
								
							}else{
								//按种子类型导出
								
							}
						}
					};
				builder.setItems(R.array.hobby, listener);
				dialog = builder.create();
				break;
		}
		return dialog;
	}

	/**
	 * 捕捉back
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			if(istoday){
				//今天
				Intent counter1 = new Intent(GridActivity.this, HomeActivity.class);
				startActivity(counter1);
				finish();
			}else{
				//历史
				Intent counter1 = new Intent(GridActivity.this, CalendarView.class);
				startActivity(counter1);
				finish();
			}
			
			return true;
		}
		
		return super.onKeyDown(keyCode, event);
	}
}  
